package com.lt.crm.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

import com.lt.crm.pojo.SysRight;
import com.lt.crm.service.SysRightService;
import javax.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


@Configuration
public class ShiroConfig {
    //注入Redis参数，从application.properties
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.timeout}")
    private int timeout;

    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(port);
        redisManager.setTimeout(timeout);
        redisManager.setPassword(password);
        return redisManager;
    }

    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        //缓存名称
        redisCacheManager.setPrincipalIdFieldName("usrName");
        //缓存时间
        redisCacheManager.setExpire(1800);
        return redisCacheManager;
    }

    /**
     * 开启Shiro注解（如：R俄区i热是R哦乐山，@ReqiresPermission）
     * 需借助SpringAOP扫描使用Shiro的注解的类，并在必要时进行安全逻辑验证
     * 配置一下两个bean（DefaultAdbisorAutoProxyCreator）和
     * AuthorizationAttributeSourceAdvisor
     */
    // 定义Bean
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
        // 创建DefaultAdvisorAutoProxyCreator对象
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        // 设置代理目标类
        advisorAutoProxyCreator.setProxyTargetClass(true);
        // 返回创建的对象
        return advisorAutoProxyCreator;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    //回话操作
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }

    //会话管理
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionDAO(redisSessionDAO());
        return sessionManager;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //使用md5算法进行加密
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        //加密次数
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
    }

    @Bean
    public MyShiroRealm myShiroRealm() {
        MyShiroRealm shiroRealm = new MyShiroRealm();
        //设置启用缓存，并设置缓存名称
        shiroRealm.setCachingEnabled(true);
        shiroRealm.setAuthorizationCachingEnabled(true);
        shiroRealm.setAuthorizationCacheName("authorizationCache");
        //设置凭证（密码）匹配器
        shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return shiroRealm;
    }
    // 使用@Bean注解，在Spring容器中创建一个名为myShiroRealm的MyShiroRealm的Bean实例
    // MyShiroRealm是自定义的Shiro领域(Realm)实现，用于进行身份验证和授权

    // 使用@Bean注解，在Spring容器中创建一个名为securityManager的DefaultWebSecurityManager的Bean实例
    // DefaultWebSecurityManager是Shiro的安全管理器，它负责协调安全相关的操作
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 注入自定义的Realm到安全管理器中
        // 这样安全管理器就知道如何获取用户信息和验证用户凭证了
        securityManager.setRealm(myShiroRealm());
        //SecurityUtils.setSecurityManager(securityManager);
        securityManager.setCacheManager(cacheManager());
        //注入会话管理器
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }

    @Resource
    private SysRightService sysRightService;

    // 使用@Bean注解，在Spring容器中创建一个名为shiroFilterFactoryBean的ShiroFilterFactoryBean的Bean实例
    // ShiroFilterFactoryBean是Shiro提供的用于配置Shiro过滤链的工厂Bean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 注入SecurityManager到ShiroFilterFactoryBean中
        // ShiroFilterFactoryBean会使用这个SecurityManager来构建Shiro的过滤器链
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 注意：这里通常还需要配置shiroFilterFactoryBean的过滤链定义（如登录页面、需要保护的URL等）
        // 但由于代码片段中没有展示这部分，所以这里只是简单地返回了shiroFilterFactoryBean实例
        //权限验证：使用Filter控制资源（URL）的访问
        shiroFilterFactoryBean.setLoginUrl("/index");

        shiroFilterFactoryBean.setSuccessUrl("/main");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");//没有权限跳转403页面
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();//必须使用LinkedHashMap（有序集合）
        //配置可以匿名访问的资源：静态资源

        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/localjs/**", "anon");
        filterChainDefinitionMap.put("/localcss/**", "anon");
        filterChainDefinitionMap.put("/dologin", "anon");
        //filterChainDefinitionMap.put("/user/doLogin", "anon");
        filterChainDefinitionMap.put("/logout", "logout");

        //配置权限验证：特定资源（URL）的访问必须具备指定的权限才能访问
        //静态演示
        /*filterChainDefinitionMap.put("/user/add", "perms[用户添加]");
        filterChainDefinitionMap.put("/user/edit", "perms[用户编辑]");*/
        List<SysRight> rights = sysRightService.list();
        for (SysRight right : rights) {
            if (right.getRightUrl() != null && !right.getRightUrl().trim().equals("")) {
                filterChainDefinitionMap.put(right.getRightUrl(), "perms[" + right.getRightCode() + "]");
            }
        }
        filterChainDefinitionMap.put("/**", "authc");//必须放在过滤链的最后面
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}
